package cn.melonlib.cores.commons.comp.utils;

import cn.melonlib.cores.aop.comp.web.WebInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class UriPathUtils {

    public static final Pattern URL_REGEX=Pattern.compile("^https?://.+$");

    public static Pattern IP_V4_REGEX=Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$");
    @Resource
    @Lazy
    private WebInfo webinfo;

    @Value("${system.config.ignore_domains:localhost}")
    private List<String> ignoreDomains;

    public String getHttpAbsolutePath(String path){
        WebInfo.ServerInfo serverInfo=webinfo.getServerInfo();
        if(URL_REGEX.matcher(path).matches()) {
            return path;
        }
        return getRootPath()+path;
    }

    public String getRootPath(){
        WebInfo.ServerInfo serverInfo=webinfo.getServerInfo();
        if (serverInfo == null || ignoreDomains.contains(serverInfo.getDomain())||
                IP_V4_REGEX.matcher(serverInfo.getDomain()).matches()
        ) {
            return webinfo.getServiceOrigin().replaceAll("/\\s*$", "");
        }
        return webinfo.getServerInfo().getPrefix();
    }

}
